package com.matrix.admin.controller;

import com.matrix.api.merchant.MerchantApi;
import com.matrix.api.merchant.vo.ShopBriefInfoVO;
import com.matrix.api.user.UserApi;
import com.matrix.api.user.vo.UserInfoVO;
import com.matrix.common.domain.PageResult;
import com.matrix.common.domain.Result;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author 有点甜
 * @since 2025/7/30
 */
@RestController
@RequestMapping("/admin/manage")
@RequiredArgsConstructor
public class ManagementController {

    @DubboReference(check = false)
    private UserApi userApi;

    @DubboReference(check = false)
    private MerchantApi merchantApi;

    @GetMapping("/users")
    @PreAuthorize("hasAuthority('ADMIN')")
    public Result<PageResult<UserInfoVO>> listUsers(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String nickname) {
        PageResult<UserInfoVO> pageResult = userApi.listUsersByPage(pageNum, pageSize, phone, nickname);
        return Result.success(pageResult);
    }

    @PutMapping("/user/{userId}/status")
    @PreAuthorize("hasAuthority('ADMIN')")
    public Result<Void> updateUserStatus(@PathVariable Long userId, @RequestBody Map<String, Integer> payload) {
        Integer status = payload.get("status");
        userApi.updateUserStatus(userId, status);
        return Result.success();
    }

    @GetMapping("/merchants")
    @PreAuthorize("hasAuthority('ADMIN')")
    public Result<PageResult<ShopBriefInfoVO>> listMerchants(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String shopName,
            @RequestParam(required = false) String ownerPhone) {
        PageResult<ShopBriefInfoVO> pageResult = merchantApi.listMerchantsByPage(pageNum, pageSize, shopName, ownerPhone);
        return Result.success(pageResult);
    }

    @PutMapping("/merchant/{shopId}/status")
    @PreAuthorize("hasAuthority('ADMIN')")
    public Result<Void> updateShopStatus(@PathVariable Long shopId, @RequestBody Map<String, Integer> payload) {
        Integer status = payload.get("status");
        merchantApi.updateShopStatus(shopId, status);
        return Result.success();
    }
}